<template>
  <div class="table">
    <div class="table_top">
      <div class="table_top_L">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="类型">
            <el-select v-model="formInline.type" placeholder="类型" clearable>
              <el-option label="赛事推荐位" :value="0"></el-option>
              <el-option label="赛事瞬间" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="formInline.id" placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="联赛id">
            <el-select v-model="formInline.contestId" placeholder="联赛id" clearable filterable>
              <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="inquire">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="openAddDialog">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="tableData"
      width="10%"
      height="100%"
      border
      stripe
      highlight-current-row
      v-loading="listLoading"
      ref="table"
      current-row-key="id"
      row-key="id"
      key="id"
      column-key="id"
      @selection-change="selectionChange"
    >
      <el-table-column prop="contestId" label="联赛id" width="60"></el-table-column>
      <el-table-column label="类型">
        <template slot-scope="scope">
          {{ scope.row.type == 0 ? '赛事推荐位' : '赛事瞬间' }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.img" alt="" style="height: 50px; width: auto;" />
        </template>
      </el-table-column>
      <el-table-column prop="jumpLink" label="跳转链接"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="danger" size="small" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog title="新增Banner" :visible.sync="addDialogVisible">
      <el-form :model="newBanner" ref="addForm">
        <el-form-item label="跳转链接">
          <el-radio-group v-model="newBanner.type">
            <el-radio :label="0">赛事推荐位</el-radio>
            <el-radio :label="1">赛事瞬间</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="title" required>
          <el-input v-model="newBanner.title"></el-input>
        </el-form-item>

        <el-form-item label="联赛id" prop="contestId" required>
          <el-select v-model="newBanner.contestId" placeholder="选择联赛id" clearable>
            <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="img">
          <div v-loading="isLoading" element-loading-text="正在上传...">
            <img v-if="uploadUrl" :src="uploadUrl" style="height:100px;width:100px;" />
            <input type="file" @change="handleFileChange" ref="fileInput" />
          </div>
        </el-form-item>

        <el-form-item label="跳转链接" prop="jumpLink">
          <el-input v-model="newBanner.jumpLink" placeholder="跳转链接"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeBanner">取 消</el-button>
        <el-button type="primary" @click="addNewBanner">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addBanner, bannerList, delBanner, contestListDown, uploadPhoto } from '@/api/table'

export default {
  data() {
    return {
      tableData1: [],
      tableData: [],
      listLoading: true,
      form: {
        contestId: '',
        img: '',
        jumpLink: '',
        title: ''
      },
      formInline: {
        id: '',
        contestId: '',
        state: '',
        type: ''
      },
      newBanner: {
        // 新增的 Banner 数据
        title: '',
        contestId: '',
        img: '',
        jumpLink: '',
        type: 0
      },
      uploadUrl: '',
      isLoading: false,
      uploadHeaders: {
        Authorization: '' // 替换为你的鉴权令牌
      },
      total: 0, // 添加总条数
      addDialogVisible: false, // 控制视频弹窗的显示与隐藏
      videoList: [], // 存储视频列表数据
      previewImage: '', // 用于存储预览图片的 URL
      showPreview: false // 控制预览对话框的显示
    }
  },
  mounted() {
    this.reqData1()
    this.tableData = this.reqData()
    this.listLoading = false
  },
  methods: {
    async handleFileChange(event) {
      const file = event.target.files[0]
      if (!file) return

      this.isLoading = true // 开始加载

      // 使用 FileReader 来读取文件并生成预览图
      const fileReader = new FileReader()
      fileReader.onload = temp => {
        this.uploadUrl = temp.target.result
      }
      fileReader.readAsDataURL(file)

      const formData = new FormData()
      formData.append('file', file) // 'file' 为后端接收的字段名

      try {
        const response = await uploadPhoto(formData)
        console.log(response)
        this.newBanner.img = response.msg
        this.$message.success('图片上传成功！')
      } catch (error) {
        this.$message.error('图片上传失败！')
      } finally {
        this.isLoading = false // 上传完成，结束加载
      }
    },

    openAddDialog() {
      this.addDialogVisible = true // 打开对话框
      this.resetNewBanner() // 重置表单数据
      this.$refs.fileInput.value = null
    },
    closeBanner() {
      this.addDialogVisible = false
      this.uploadUrl = ''
      this.$refs.fileInput.value = null
    },
    resetNewBanner() {
      this.newBanner = {
        title: '',
        contestId: '',
        img: '',
        jumpLink: '',
        type: 0
      }
    },
    inquire() {
      this.reqData(1, 10000, {
        title: this.formInline.title,
        state: this.formInline.state,
        contestId: this.formInline.contestId,
        type: this.formInline.type
      })
    },
    inquire1() {
      this.reqData(1, 10000, {
        contestId: this.newBanner.contestId
      })
    },
    selectionChange(selection) {
      this.selectionLength = selection.length
    },
    async addNewBanner() {
      await addBanner(this.newBanner)
      this.addDialogVisible = false
      this.uploadUrl = ''
      this.inquire1()
    },
    // 请求
    reqData(pageNum = 1, pageSize = 10000, query = {}) {
      const params = { pageNum, pageSize, ...query }
      bannerList(params).then(async res => {
        const promises = res.rows.map(async item => {
          // 根据需要拼接 URL
          item.img = `https://boyubasketball.oss-cn-shanghai.aliyuncs.com/${item.img}`
          return item
        })
        this.tableData = await Promise.all(promises)
      })
    },
    reqData1(pageNum = 1, pageSize = 10000, query = {}) {
      const params = { pageNum, pageSize, ...query }
      contestListDown(params).then(res => {
        this.tableData1 = res.data.map(item => ({
          value: item.id,
          label: item.name // 假设 id 是数字类型
        }))
      })
    },
    async del(id) {
      try {
        await delBanner(id)
        this.inquire()
      } catch (e) {
        alert('删除失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-flow: column;
  box-sizing: border-box;

  .table_top {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;

    .table_top_L {
      text-align-last: left;
      flex: 1;
      overflow: hidden;
    }
  }

  .table_bottom {
    margin-top: 10px;
  }

  height: 100%;
}
</style>
<style>
.table .el-table {
  transition: all ease-in-out 0.3s;
}

.table .el-table td,
.table .el-table th {
  text-align: center;
}

.table .el-dialog {
  text-align: left;
}

.table .el-dialog .line {
  text-align: center;
}

.el-image-viewer__close {
  background-color: #fff;
}

/* 重新覆盖原来的样式，原来的样式是.el-drawer获取焦点时的outline */
.el-image-viewer__wrapper:focus {
  outline: none;
}
</style>
